package com.zyy.servlet;

import com.zyy.pojo.User;
import com.zyy.service.user.UserService;
import com.zyy.service.user.impl.UserServiceImpl;
import com.zyy.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: LoginServlet
 * @Description: TODO 类描述
 * @Author: zyy
 * @Date: 2022/01/09 11:36
 * @Version: 1.0
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet---start----");
        //用户前端输入的用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        //调用业务层
        UserService userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);
        if (user != null) {
            //查有此人
            //将用户的信息放到session中
            req.getSession().setAttribute(Constants.USER_SESSION, user);
            //跳转到主页
            resp.sendRedirect("jsp/frame.jsp");
        } else {
            //查无此人
            //转发回登录页面，并提示它用户名或者密码错误
            req.setAttribute("error", "用户名或者密码错误");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
